<?php


namespace app\common;


use Exception;
use PHPExcel_Reader_Excel5;
use PHPExcel_Reader_Excel2007;
use PHPExcel_Writer_Excel5;
use PHPMailer\PHPMailer\PHPMailer;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Facade;
use think\facade\Config;


class Tools extends Facade
{

    protected static function getFacadeClass()
    {
        return __CLASS__;
    }

    /**
     * 导出Excel文件
     * @param string[] $titles 标题
     * @param string[] $contents 内容
     * @param string $savePath 保存路径
     * @param int[] $setWidths 设置表格宽
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public static function mb_ExportExcel($titles, $contents, $savePath, $setWidths = null)
    {
        error_reporting(0);

        require_once $_SERVER['DOCUMENT_ROOT'] . '/static/PHPExcel/PHPExcel.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/static/PHPExcel/PHPExcel/IOFactory.php';

        if (!is_array($titles)) {
            throw new Exception('Titles is not array!', -1);
            return;
        }

        if (!is_array($contents)) {
            throw new Exception('Content is not array!', -1);
            return;
        }



        $objPHPExcel = new \PHPExcel();
        $pConfig = Config::get('project');

        $objProps = $objPHPExcel->getProperties();
        $objProps->setCreator($pConfig['name']); //作者
        $objProps->setLastModifiedBy($pConfig['name']); //最后修改
        $objProps->setTitle($pConfig['name']); //标题
        $objProps->setSubject($pConfig['name']);  //设置主题
        $objProps->setDescription($pConfig['name']);  //设置描述
        $objProps->setKeywords($pConfig['name']); //设置关键字

        $objPHPExcel->setActiveSheetIndex(0);

        $letter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        //設置標題，標題個數最多26個，超過有錯
        for ($i = 0; $i < count($titles); $i++) {
            $t = $letter[$i];
            $objPHPExcel->getActiveSheet()->setCellValue($t . '1', $titles[$i]);//可以指定位置
            $objPHPExcel->getActiveSheet()->getStyle($t . '1')->getFont()->setBold(true);
        }
        //設置內容，內容列數最多26個，超過有錯
        for ($i = 0; $i < count($contents); $i++) {
            for ($j = 0; $j < count($contents[$i]); $j++) {
                $t = $letter[$j];
                $objPHPExcel->getActiveSheet()->setCellValue($t . ($i + 2), $contents[$i][$j]);//可以指定位置
            }
        }

        if (isset($setWidths)) {
            for ($i = 0; $i < count($setWidths); $i++) {
                //跳过没有设置的单元格
                if (isset($setWidths[$i]))
                    $objPHPExcel->getActiveSheet()->getColumnDimension($letter[$i])->setWidth($setWidths[$i]);#设置单元格宽度
            }
        }
        $objWriters = new PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriters->save($savePath);
    }

    /**
     * 导入Excel文件
     * @param $file 文件路径
     * @return array
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public static function mb_ImportExcel($file)
    {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/static/PHPExcel/PHPExcel.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/static/PHPExcel/PHPExcel/IOFactory.php';

//        error_reporting(E_ALL ^ E_DEPRECATED);
        error_reporting(0);
//        ini_set('memory_limit','1024M'); //升级为256M内存

        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('memoryCacheSize' => '16MB');

        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $PHPReader = new PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($file)) {

            $PHPReader = new PHPExcel_Reader_Excel5();//建立reader对象，excel—2007以前格式
            if (!$PHPReader->canRead($file)) {
                $msg = '不是excel格式文件';
                throw new Exception($msg, -1);
            }
        }

        $PHPExcel = $PHPReader->load($file); //加载excel对象
        $sheet = $PHPExcel->getSheet(0); //获取指定的sheet表
        $rows = $sheet->getHighestRow();//行数
        $cols = $sheet->getHighestColumn();//列数

        $data = array();
        for ($i = 1; $i <= $rows; $i++) { //行数是以第1行开始
            $count = 0;
            for ($j = 'A'; $j <= $cols; $j++) { //列数是以A列开始
                $value = $sheet->getCell($j . $i)->getValue();
                $data[$i - 1][$count] = (string)$sheet->getCell($j . $i)->getValue();
                $count += 1;
            }
        }
        return $data;
    }

    /**
     * 上傳圖片到七牛雲
     * @param $uploadName
     * @throws Exception
     */
    public static function mb_UploadQiNiu($uploadName)
    {
        $accessKey = Config::get('qny')['AccessKey'];
        $secretKey = Config::get('qny')['SecretKey'];
        $bucket = Config::get('qny')['BUCKET'];
        $domain = Config::get('qny')['Domain'];

        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();

        $file = $_FILES[$uploadName];
        if ($file["error"] > 0) {
            throw new Exception($file['error']);
            return;
        }

        $temp = explode('.', $file['name']);
        $key = md5(time() . $file['name']) . '.' . end($temp);
        list($ret, $err) = $uploadMgr->putFile($token, $key, $file['tmp_name']);
        if ($err != null) {
            $err['result'] = false;
            return $err;
        } else {
            $ret['result'] = true;
            $ret['key'] = $domain . $ret['key'];
            return $ret;
        }
    }

    /**
     * 刪除文件夾（包括文件夾下的文件）
     * @param $dir
     * @return bool
     */
    public static function mb_DeleteDirectory($dir)
    {
        //先删除目录下的文件：
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    self::mb_DeleteDirectory($fullpath);
                }
            }
        }

        closedir($dh);
        //删除当前文件夹：
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送邮件
     * @param $recipients 收件人['address','name']
     * @param $subject 主题
     * @param $body HTML内容
     * @param $altBody 不支持html内容的时候，显示的内容
     * @param array $attachments 附件路径[]
     * @return \RetData
     */
    public static function mb_SendEmail($recipients, $subject, $body, $altBody = '', $attachments = array())
    {

        $username = Config::get('Email')['Username'];
        $password = Config::get('Email')['Password'];
        $nickname = Config::get('Email')['Nickname'];

        $mail = new PHPMailer(true);
        try {
            //服务器配置
            $mail->CharSet = "UTF-8";                     //设定邮件编码
            $mail->SMTPDebug = 0;                        // 调试模式输出
            $mail->isSMTP();                             // 使用SMTP
            $mail->Host = 'smtp.163.com';                // SMTP服务器
            $mail->SMTPAuth = true;                      // 允许 SMTP 认证
            $mail->Username = $username;                // SMTP 用户名  即邮箱的用户名
            $mail->Password = $password;             // SMTP 密码  部分邮箱是授权码(例如163邮箱)
            $mail->SMTPSecure = 'ssl';                    // 允许 TLS 或者ssl协议
            $mail->Port = 465;                            // 服务器端口 25 或者465 具体要看邮箱服务器支持

            $mail->setFrom($username, $nickname);  //发件人

            foreach ($recipients as $key => $val) {
                $mail->addAddress($val['address'], $val['name']);  // 收件人
            }

            //$mail->addAddress('ellen@example.com');  // 可添加多个收件人
            $mail->addReplyTo($username, $nickname); //回复的时候回复给哪个邮箱 建议和发件人一致
            //$mail->addCC('cc@example.com');                    //抄送
            //$mail->addBCC('bcc@example.com');                    //密送

            //发送附件
            // $mail->addAttachment('../xy.zip');         // 添加附件
            // $mail->addAttachment('../thumb-1.jpg', 'new.jpg');    // 发送附件并且重命名

            foreach ($attachments as $key => $val) {
                $mail->addAttachment($val);
            }

            //Content
            $mail->isHTML(true);                                  // 是否以HTML文档格式发送  发送后客户端可直接显示对应HTML内容
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = $altBody;

            $mail->send();

            $result = true;
            $message = '邮件发送成功';
        } catch (\Exception $e) {
//            echo '邮件发送失败: '. $mail->ErrorInfo;
            $result = false;
            $message = '邮件发送失败:' . $mail->ErrorInfo;
        }
        $retData = new \RetData();
        $retData->m_Result = $result;
        $retData->m_Message = $message;
        return $retData;
    }
    /**
     * 输出日志
     *
     * @param string $word
     * @param string $show
     */
    public static function mb_LogResult($word = '', $show = false) {
        $logWord = '[' . date ( 'Y-m-d H:i:s' ) . '] ' . $word . "\r\n";
        $logPath = dirname ( __FILE__ ) . '\\Log\\';
        $logName = 'Log_' . date ( 'Y-m-d' ) . '.txt';
        $logFile = $logPath . $logName;

        if (! is_dir ( $logPath )) {
            mkdir ( $logPath );
        }
        $fp = null;
        if (! is_file ( $logFile )) {
            $fp = fopen ( $logFile, "w" );
        } else {
            $fp = fopen ( $logFile, "a" );
        }
        flock ( $fp, LOCK_EX );
        fwrite ( $fp, $logWord );
        flock ( $fp, LOCK_UN );
        fclose ( $fp );

        if ($show)
            echo $logWord;
    }

    public static function mb_GetWeekday(){
        $weekarray=array("日","一","二","三","四","五","六");
        //先定义一个数组
        return "星期".$weekarray[date("w")];
    }
}